import createPersistedState from "vuex-persistedstate";
import { getDashboardHotels } from "@/api/information.js";
export default {
  namespaced: true,
  state: {
    hotelList: [],
    currentHotelId: null,
  },
  mutations: {
    SET_HOTEL_LIST(state, list) {
      state.hotelList = list;
      // 注意：这里可能导致自动选择第一个酒店，建议移除
      // if (list.length > 0 && !state.currentHotelId) {
      //   state.currentHotelId = list[0].hotelId;
      // }
    },
    SET_CURRENT_HOTEL(state, id) {
      const isValidHotel = state.hotelList.some(
        (hotel) => hotel.hotelId === id
      );
      if (isValidHotel) {
        state.currentHotelId = id;
      } else {
        console.warn("无效的酒店ID:", id);
        state.currentHotelId =
          state.hotelList.length > 0 ? state.hotelList[0].hotelId : null;
      }
    },
  },
  getters: {
    currentHotel: (state) => {
      return state.hotelList.find(
        (hotel) => hotel.hotelId === state.currentHotelId
      );
    },
  },
  actions: {
    async fetchHotelList({ commit, dispatch }) {
      try {
        const res = await getDashboardHotels();
        commit("SET_HOTEL_LIST", res.data || []);
      } catch (error) {
        commit("SET_HOTEL_LIST", []);
        dispatch(
          "app/setNotification",
          {
            type: "error",
            message: "Failed to obtain the hotel list. Please try again",
          },
          { root: true }
        );
      }
    },
  },
  plugins: [
    createPersistedState({
      paths: ["hotel.currentHotelId"],
    }),
  ],
};
